<template>
  <Form
    ref="formCom"
    :validation-schema="mySchema"
    v-slot="{ errors }"
    class="xtx-form"
  >
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{ nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          :class="{ err: errors.mobile }"
          v-model="form.mobile"
          name="mobile"
          class="input"
          type="text"
          placeholder="绑定的手机号"
        />
      </div>
      <div v-if="errors.mobile" class="error">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          :class="{ err: errors.code }"
          v-model="form.code"
          name="code"
          class="input"
          type="text"
          placeholder="短信验证码"
        />
        <span class="code" @click="send">{{
          countTime === 0 ? "发送验证码" : `${countTime}秒后发送`
        }}</span>
      </div>
      <div v-if="errors.code" class="error">{{ errors.code }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即绑定</a>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import { ref, reactive } from 'vue'
import schema from '@/utils/vee-validate-schema'

import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { useCountDown } from '@/hooks'
import Message from '@/components/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

// 表单校验
function useFormValidate () {
  // 表单数据对象
  const form = reactive({
    mobile: null,
    code: null
  })
  // 校验规则对象
  const mySchema = {
    mobile: schema.mobile,
    code: schema.code
  }
  return { form, mySchema }
}

// 发验证码
function sendCode (form) {
  // 发送验证码
  const { countTime, start } = useCountDown(60)
  const formCom = ref(null)
  const send = async () => {
    const valid = schema.mobile(form.mobile)
    if (valid === true) {
      // 通过
      if (countTime.value === 0) {
        // 没有倒计时才可以发送
        await userQQBindCode(form.mobile)
        Message({ type: 'success', text: '发送成功' })
        // 开启倒计时
        start()
      }
    } else {
      // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
      formCom.value.setFieldError('mobile', valid)
    }
  }
  return { send, formCom, countTime }
}
export default {
  name: 'CallbackBind',
  components: {
    Form, Field
  },
  props: {
    unionId: {
      type: String
    }
  },
  setup (props) {
    // 已注册未绑定
    // 名称和头像
    const nickname = ref('')
    const avatar = ref('')
    if (window.QC.Login.check()) {
      window.QC.api('get_user_info').success(res => {
        console.log('授权登录后可以获取：', res)
        avatar.value = res.data.figureurl_qq_1
        nickname.value = res.data.nickname
      })
    }

    // 1. 表单校验
    const { form, mySchema } = useFormValidate()

    // 2. 发验证码
    const { send, formCom, countTime } = sendCode(form)
    // 3. 立即提交绑定QQ账号
    const store = useStore()
    const router = useRouter()
    const submit = async () => {
      const valid = await formCom.value.validate()
      console.log('bind phone:', valid)
      if (valid.valid) {
        userQQBindLogin({
          unionId: props.unionId,
          ...form
        }).then(({ result }) => {
          // 实现和之前登录一样的逻辑
          // 1. 存储用户信息
          store.commit('user/setUser', result)
          // 2. 跳转到来源页或者首页
          router.push('/')
          // 3. 成功提示
          Message({ type: 'success', text: 'QQ绑定成功' })
        }).catch(e => {
          Message({ type: 'error', text: '绑定失败' })
        })
      }
    }

    return {
      nickname,
      avatar,
      form,
      mySchema,
      send,
      formCom,
      countTime,
      submit
    }
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
